package com.app.twth.ui.tally;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.RadioGroup;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.app.twth.BR;
import com.app.twth.R;
import com.app.twth.app.AppRouter;
import com.app.twth.app.Constant;
import com.app.twth.base.BaseActivity;
import com.app.twth.databinding.ActivityTallyBinding;
import com.app.twth.databinding.DialogTallyDetailBinding;
import com.app.twth.net.OkHttpUtils;
import com.app.twth.ui.tally.damagesku.DamageSkuActivity;
import com.app.twth.ui.tally.lpn.TallyLPNActivity;
import com.app.twth.ui.tally.sku.TallySkuActivity;
import com.app.twth.utils.DividerItemDecoration;
import com.app.twth.utils.MyDialogUtil;
import com.app.twth.utils.PreferencesUtil;
import com.app.twth.utils.ToastUtil;
import com.app.twth.utils.Utils;

import java.util.ArrayList;
import java.util.List;

public class TallyActivity extends BaseActivity<ActivityTallyBinding, TallyViewModel> {
    private String TAG = getClass().getSimpleName();

    private int type, typ;

    private Tally tally;
    private long timeMillis;
    private TallyAdapter adapter;
    private AlertDialog dialogTallyDetail;
    private List<Tally> tallyList = new ArrayList<>();
    private List<TallyDetails> tallyDetailList;

    @Override
    protected void initListener() {
        viewModel.getTallyList(type);
        binding.rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.tv_tallying_list:
                        type = 0;
                        break;
                    case R.id.tv_completed_list:
                        type = 1;
                        break;
                }
                viewModel.getTallyList(type);
            }
        });
        viewModel.tallyingLiveData.observe(this, data -> {
            if (type == 0) {
                tallyList.clear();
                tallyList.addAll(data);
                adapter.setData(tallyList, type);
            }
        });
        viewModel.tallyedLiveData.observe(this, data -> {
            if (type == 1) {
                tallyList.clear();
                tallyList.addAll(data);
                adapter.setData(tallyList, type);
            }
        });
        viewModel.tallyDetailsLiveData.observe(this, data -> {
            tallyDetailList = data;
            showTallyDetailDialog();
        });
        viewModel.tallySkuDetailsLiveData.observe(this, data -> {
            tallyDetailList = viewModel.tallyDetailsLiveData.getValue();
            if (tallyDetailAdapter != null) {
                tallyDetailAdapter.setData(tallyDetailList, -1);
            }
        });
        viewModel.isLoading.observe(this, b -> {
            if (b.isShow()) {
                showProgressDialog(b.getMsg());
            } else {
                dismissProgressDialog();
            }
        });
        viewModel.completedLiveData.observe(this, b -> {
            viewModel.getTallyList(type);
        });
        viewModel.errorResultCode.observe(this, code -> {
            showHint((String) code);
        });
        viewModel.code.observe(this, code -> {
            Log.e(TAG, "code" + viewModel.code.getValue());
        });
    }

    @Override
    protected String setTitle() {
        return "Tally(Container)";
    }

    @Override
    protected int initViewModelId() {
        return BR.viewModel;
    }

    @Override
    protected void initData() {
        setNext("");
        Bundle bundle = getIntent().getBundleExtra(AppRouter.K_EXTRA);
        typ = bundle.getInt("typ", 1);
        if (typ == 2) {
            setTitle("Damage:Container");
        }
        binding.tvCode.requestFocus();

        adapter = new TallyAdapter(this, tallyList, position -> {
//            if (type == 1) {
//                return;
//            }
            tally = position;
            showCheck(tally);

        }, position -> {
            tally = position;
            viewModel.getTallyDetail(tally.getOrderId());
        });
        binding.recyclerview.setHasFixedSize(true);
        binding.recyclerview.setItemAnimator(new DefaultItemAnimator());

        LinearLayoutManager layoutManager1 = new LinearLayoutManager(this);
        layoutManager1.setOrientation(LinearLayoutManager.VERTICAL);
        binding.recyclerview.setLayoutManager(layoutManager1);
        //添加装饰类
        binding.recyclerview.addItemDecoration(new DividerItemDecoration(mContext, DividerItemDecoration.VERTICAL_LIST));
        binding.recyclerview.setAdapter(adapter);

        binding.tvCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                setSearchData();
            }
        });
    }

    private void setSearchData() {
        if (viewModel.tallyingLiveData.getValue() == null || viewModel.tallyingLiveData.getValue().size() == 0) {
            return;
        }
        if (type != 0) {
            type = 0;
            binding.tvTallyingList.setChecked(true);
        }

        String container = binding.tvCode.getText().toString();
        if (Utils.isEmpty(container)) {
            tallyList.clear();
            tallyList.addAll(viewModel.tallyingLiveData.getValue());
            adapter.setData(tallyList, type);
        } else {
            ArrayList<Tally> tallies = new ArrayList<>();
            for (Tally tally : viewModel.tallyingLiveData.getValue()) {
                if (tally.getContainerNo().toLowerCase().contains(container.toLowerCase())) {
                    tallies.add(tally);
                }
            }
            adapter.setData(tallies, type);
        }
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        initScan();
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        unScan();
    }

    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_reset:
                binding.tvCode.setText("");
                break;
            case R.id.tv_tallying_list:
                if (System.currentTimeMillis() - timeMillis < 500) {//两秒内触发一次
                    return;
                }
                timeMillis = System.currentTimeMillis();
                type = 0;
                setType();
                break;
            case R.id.tv_completed_list:
                if (System.currentTimeMillis() - timeMillis < 500) {//两秒内触发一次
                    return;
                }
                timeMillis = System.currentTimeMillis();
                type = 1;
                setType();
                break;
            case R.id.tv_next:
                if (System.currentTimeMillis() - timeMillis < spaceTime) {//两秒内触发一次
                    return;
                }
                timeMillis = System.currentTimeMillis();
                String container_no = binding.tvCode.getText().toString();
                if (Utils.isEmpty(container_no)) {
                    ToastUtil.showToast("Please enter container no.");
                    return;
                }
                if (viewModel.tallyingLiveData.getValue() == null || viewModel.tallyingLiveData.getValue().size() == 0) {
                    ToastUtil.showToast("The container number does not exist or has been completed.");
                    return;
                }
                Tally tally1 = null;
                for (Tally tally : viewModel.tallyingLiveData.getValue()) {
                    if (tally.getContainerNo().equalsIgnoreCase(container_no)) {
                        tally1 = tally;
                    }
                }
                if (tally1 == null) {
                    ToastUtil.showToast("The container number does not exist or has been completed.");
                    return;
                }
                showCheck(tally1);
                break;
        }
    }

    @Override
    public void getScanninCode() {
        super.getScanninCode();
        binding.tvCode.setText(barcodeStr);
    }


    private void setType() {
        tallyList.clear();
        adapter.setData(tallyList, type);
//        getPresenter().getTallyContainerNo(type);
    }

    private void showTallyDetailDialog() {
        dialogTallyDetail = MyDialogUtil.getDialog(mContext, initTallyDetailDialogView(), Gravity.CENTER);
        dialogTallyDetail.setCanceledOnTouchOutside(true);
        dialogTallyDetail.show();
    }

    TallyDetailAdapter tallyDetailAdapter;
    String hint = "";

    private View initTallyDetailDialogView() {
        DialogTallyDetailBinding dialogBinding = DialogTallyDetailBinding.inflate(getLayoutInflater());
        hint = "";

        if (Utils.isEmpty(tally.getStatus())) {
            dialogBinding.tvTitle.setText("Detail(" + tally.getContainerNo() + ")");
            dialogBinding.viewLine.setVisibility(View.GONE);
            dialogBinding.tvConfirm.setVisibility(View.GONE);
            dialogBinding.tvCancel.setText("Close");
        } else if (tally.getStatus().equals("4")) {//理货中
            dialogBinding.tvTitle.setText("Tally(" + tally.getContainerNo() + ")");

            for (TallyDetails tallyLPN : tallyDetailList) {
                if (tallyLPN.getSkuQty() == null) {
                    hint = hint + tallyLPN.getSku() + "  ";
                } else if (tallyLPN.getTalliedQty() == null) {
                    hint = hint + tallyLPN.getSku() + "  ";
                } else if (tallyLPN.getSkuQty() - tallyLPN.getTalliedQty() != 0) {
                    hint = hint + tallyLPN.getSku() + "  ";
                }
            }
            dialogBinding.layoutQty.setVisibility(View.VISIBLE);
            if (!Utils.isEmpty(hint)) {
                dialogBinding.tvExceptionHint.setVisibility(View.VISIBLE);
                dialogBinding.etPassword.setVisibility(View.VISIBLE);
                dialogBinding.tvPasswordHint.setVisibility(View.VISIBLE);
                dialogBinding.tvExceptionHint.setText("The tally qty of following sku doesn't match the forecast qty: " + hint);

                String str = dialogBinding.tvExceptionHint.getText().toString();
                SpannableString spannable = new SpannableString(str);
                ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(Color.RED);
                spannable.setSpan(foregroundColorSpan, "The tally qty of following sku doesn't match the forecast qty: ".length(), str.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

                dialogBinding.tvExceptionHint.setMovementMethod(LinkMovementMethod.getInstance());//不设置点击会失效
                dialogBinding.tvExceptionHint.setHintTextColor(this.getResources().getColor(R.color.transparent));//不设置会有背景色
                dialogBinding.tvExceptionHint.setText(spannable);
            }
            if (!PreferencesUtil.getBoolean(this, Constant.isManager)) {
                dialogBinding.layoutQty.setVisibility(View.GONE);
                dialogBinding.etPassword.setVisibility(View.GONE);
                dialogBinding.tvPasswordHint.setVisibility(View.GONE);
                dialogBinding.tvConfirm.setVisibility(View.GONE);
                dialogBinding.tvCancel.setText("Close");
            }
        } else {
            dialogBinding.tvTitle.setText("Detail(" + tally.getContainerNo() + ")");
            dialogBinding.viewLine.setVisibility(View.GONE);
            dialogBinding.tvConfirm.setVisibility(View.GONE);
            dialogBinding.tvCancel.setText("Close");
        }
        dialogBinding.tvTitleHint1.setText("SKU(" + tallyDetailList.size() + ")");
        tallyDetailAdapter = new TallyDetailAdapter(this, tallyDetailList, position -> {
            TallyDetails tallyDetail = tallyDetailList.get(position);
            if (tallyDetail.isClick()) {//收起
                tallyDetail.setClick(!tallyDetail.isClick());
                if (tallyDetailAdapter != null) {
                    tallyDetailAdapter.setData(tallyDetailList, -1);
                }
                return;
            }

            if (tallyDetail.getLpnsList() == null || tallyDetail.getLpnsList().size() == 0) {//没有数据去请求
                viewModel.getTallySkuDetail(position, tallyDetailList.get(position).getOrderItemId());
            } else {
                tallyDetail.setClick(!tallyDetail.isClick());
                if (tallyDetailAdapter != null) {
                    tallyDetailAdapter.setData(tallyDetailList, -1);
                }
            }
        }
        );

        LinearLayoutManager layoutManager1 = new LinearLayoutManager(this);
        layoutManager1.setOrientation(LinearLayoutManager.VERTICAL);
        dialogBinding.recyclerviewDetail.setLayoutManager(layoutManager1);
        dialogBinding.recyclerviewDetail.setAdapter(tallyDetailAdapter);

        dialogBinding.tvCancel.setOnClickListener(v -> {
            if (dialogTallyDetail != null) {
                dialogTallyDetail.dismiss();
            }
        });
        dialogBinding.tvConfirm.setText("Complete");
        dialogBinding.tvConfirm.setOnClickListener(v -> {
            String qty = dialogBinding.tvQty.getText().toString();
            if (Utils.isEmpty(qty) || (Integer.parseInt(qty) == 0)) {
                dialogBinding.tvPasswordHint.setVisibility(View.VISIBLE);
                dialogBinding.tvPasswordHint.setText("Please enter the quantity");
                return;
            }

            if (!Utils.isEmpty(hint)) {
                String password = dialogBinding.etPassword.getText().toString();
                if (TextUtils.isEmpty(password)) {
                    dialogBinding.tvPasswordHint.setText("enter password");
                    return;
                }
                String password_default = PreferencesUtil.getString(this, Constant.submit_password);
                if (TextUtils.isEmpty(password_default)) {
                    OkHttpUtils.getInstance(this).getPdaPassword();
                    dialogBinding.tvPasswordHint.setText("No permission");
                    return;
                }
                if (!password_default.equals(password)) {
                    dialogBinding.tvPasswordHint.setText("wrong password");
                    OkHttpUtils.getInstance(this).getPdaPassword();
                    return;
                }
            }

            if (dialogTallyDetail != null) {
                dialogTallyDetail.dismiss();
            }
            TallyCompletedQr tallyFinishQr = new TallyCompletedQr();
            tallyFinishQr.setOrderId(tally.getOrderId());
            tallyFinishQr.setPalletQty(Integer.parseInt(qty));
            viewModel.checkinSubmit(tallyFinishQr);
        });
        return dialogBinding.getRoot();
    }

    private void showCheck(Tally tally) {
        tally.setTyp(typ);
        Bundle bundle = new Bundle();
        bundle.putSerializable("Tally", tally);
        if (typ == 2) {
            AppRouter.showActivityForResult(mContext, DamageSkuActivity.class, bundle, Constant.ForResult2);
            return;
        }
        AppRouter.showActivityForResult(mContext, TallySkuActivity.class, bundle, Constant.ForResult2);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constant.ForResult2 && resultCode == RESULT_OK) {
            Log.e(TAG, "onActivityResult");
            type = 0;
            setType();
        }
    }
}
